package cn.touna.jss.modules.custom.carmodel.synctask;

import cn.touna.jss.modules.custom.carmodel.entity.JzgBrandEntity;
import cn.touna.jss.modules.custom.carmodel.entity.JzgModelEntity;
import cn.touna.jss.modules.custom.carmodel.entity.JzgSeriesEntity;
import cn.touna.jss.modules.custom.carmodel.mapper.JzgBrandEntityMapper;
import cn.touna.jss.modules.custom.carmodel.mapper.JzgModelEntityMapper;
import cn.touna.jss.modules.custom.carmodel.mapper.JzgSeriesEntityMapper;
import cn.touna.jss.modules.third.jzg.JingZhenGuService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * Created by Steve.Tao on 2017/11/21.
 */
@Service
public class JzgSyncModelService extends AbstractSyncModelService {

    private static final Logger logger = LogManager.getLogger();

    @Autowired
    private JingZhenGuService jingZhenGuService;

    @Autowired
    private JzgBrandEntityMapper jzgBrandEntityMapper;
    @Autowired
    private JzgSeriesEntityMapper jzgSeriesEntityMapper;
    @Autowired
    private JzgModelEntityMapper jzgModelEntityMapper;

    @Override
    public SyncModelResult refreshModel(String taskNo) {
        SyncModelResult result = new SyncModelResult();
        LocalDateTime startTime = LocalDateTime.now();
        result.setBeginTime(startTime.toString());
        logger.info("【同步车型】精真估车型同步任务开始，taskNo:{} @ time:{} ", taskNo, startTime.toString());
        Counter counter = new Counter();
        try {
            JSONObject brandsObj = jingZhenGuService.getMakeByAll();
            int errorCode = brandsObj.getInteger("errorCode");
            if (errorCode != 0) {
                result.setFailed();
                result.setMessage(brandsObj.getString("errorMessage"));
                return result;
            }

            JSONArray brandArray = getArray(brandsObj);
            for (int i = 0; i < brandArray.size(); i++) {
                JzgBrandEntity entity = parseBrand(brandArray.getJSONObject(i));
                if (entity == null) {
                    counter.count("brand.null");
                    continue;
                }
                int insertCount = jzgBrandEntityMapper.insert(entity);
                if (insertCount == 0) {
                    jzgBrandEntityMapper.updateByBrandId(entity);
                    counter.count("brand.update");
                } else {
                    counter.count("brand.insert");
                }
                refreshSeries(counter, taskNo, entity.getBrandId());
            }
            result.setSuccess();
            return result;
        } catch (Exception e) {
            logger.info("【同步车型】同步车型返回错误，taskNo:{},message:{}", taskNo, e.getMessage());
        } finally {
            LocalDateTime stopTime = LocalDateTime.now();
            result.setEndTime(stopTime.toString());
            Duration duration = Duration.between(stopTime, startTime);
            result.setCost(duration.toString());
            if (result.isSuccess())
                result.setMessage(counterToMessage(counter));
            logger.info("【同步车型】精真估车型同步任务完成，taskNo:{} cost:{}ms @ time:{} ", taskNo, duration.toString(), stopTime.toString());
        }
        result.setFailed();
        result.setMessage(counterToMessage(counter));
        return result;
    }

    private JSONArray getArray(JSONObject obj) {
        String body = obj.getString("body");
        return JSONArray.parseArray(body);
    }

    private void refreshSeries(Counter counter, String taskNo, long brandId) {
        try {

            JSONObject seriesObj = jingZhenGuService.getModels(brandId);
            if (seriesObj.getInteger("errorCode") == 0) {
                JSONArray seriesArray = getArray(seriesObj);
                for (int i = 0; i < seriesArray.size(); i++) {
                    JzgSeriesEntity entity = parseSeries(seriesArray.getJSONObject(i), brandId);
                    if (entity == null) {
                        counter.count("series.null");
                        continue;
                    }
                    int insertCount = jzgSeriesEntityMapper.insert(entity);
                    if (insertCount == 0) {
                        jzgSeriesEntityMapper.updateBySeriesId(entity);
                        counter.count("series.update");
                    } else {
                        counter.count("series.insert");
                    }
                    refreshModel(counter, taskNo, brandId, entity.getSeriesId());
                }
            } else {
                logger.info("【同步车型】获取车系返回错误，message:{}", seriesObj.getString("errorMessage"));
            }
        } catch (Exception e) {
            counter.count("series.exception");
            logger.info("【同步车型】同步车系返回错误，taskNo:{},brandId:{},message:{}", taskNo, brandId, e.getMessage());
        }
    }

    private void refreshModel(Counter counter, String taskNo, long brandId, long seriesId) {
        try {
            JSONObject modelObj = jingZhenGuService.getStyles(seriesId);
            if (modelObj.getInteger("errorCode") == 0) {
                JSONArray modelArray = getArray(modelObj);
                for (int i = 0; i < modelArray.size(); i++) {
                    JzgModelEntity entity = parseModel(modelArray.getJSONObject(i), brandId, seriesId);
                    if (entity == null) {
                        counter.count("model.nulll");
                        continue;
                    }
                    int insertCount = jzgModelEntityMapper.insert(entity);
                    if (insertCount == 0) {
                        jzgModelEntityMapper.updateByModelId(entity);
                        counter.count("model.update");
                    } else {
                        counter.count("model.insert");
                    }
                }
            } else {
                logger.info("【同步车系】获取精真估车型异常，taskNo:{},brandId:{},seriesId:{},message:{}",
                        taskNo, brandId, seriesId, modelObj.getString("errorMessage"));
            }
        } catch (Exception e) {
            counter.count("model.exception");
            logger.error("【同步车系】同步精真估车型异常，taskNo:{},brandId:{},seriesId:{},message:{}", taskNo, brandId, seriesId, e.getMessage());
        }
    }

    private JzgModelEntity parseModel(JSONObject obj, long brandId, long seriesId) {
        try {
            JzgModelEntity entity = new JzgModelEntity();
            entity.setSeriesId((int) seriesId);
            entity.setModelId(Integer.valueOf(obj.getString("styleId")));
            entity.setModelPrice(getBigDeicimal(obj.getString("msrp")));
            entity.setModelName(obj.getString("styleFullName"));
            entity.setGearType(getString(obj, "gearBox"));
            entity.setSeriesYear(getString(obj, "nextYear"));
            entity.setModelYear(getString(obj, "styleYear"));
            entity.setLiter(getString(obj, "displacement"));

            entity.setCreateUser(SYNC_USER);
            entity.setUpdateUser(SYNC_USER);
            entity.setUpdateTime(new Date());
            return entity;
        } catch (Exception e) {
            logger.error("【同步车型】精真估车系转换异常,json={},brandId={},seriesId:{},message:{}", obj.toJSONString(), brandId, seriesId, e.getMessage());
        }
        return null;
    }

    private JzgSeriesEntity parseSeries(JSONObject obj, long brandId) {
        try {
            JzgSeriesEntity entity = new JzgSeriesEntity();
            entity.setBrandId((int) brandId);
            entity.setSeriesId(Integer.valueOf(obj.getString("modelId")));
            entity.setSeriesName(obj.getString("modelName"));
            entity.setImageUrl(getString(obj, "imgUrl"));
            entity.setSeriesGroupName(getString(obj, "groupName"));
            entity.setHeat(getString(obj, "heat"));
            entity.setCreateUser(SYNC_USER);
            entity.setUpdateUser(SYNC_USER);
            entity.setUpdateTime(new Date());
            return entity;
        } catch (Exception e) {
            logger.error("【同步车型】精真估车系转换异常,json={},brandId={},message:{}", obj.toJSONString(), brandId, e.getMessage());
        }
        return null;
    }

    private JzgBrandEntity parseBrand(JSONObject obj) {
        try {
            JzgBrandEntity entity = new JzgBrandEntity();
            entity.setBrandId(Integer.valueOf(obj.getString("makeId")));
            entity.setInitial(obj.getString("groupName"));
            entity.setBrandName(obj.getString("makeName"));
            entity.setImageUrl(getString(obj, "imgUrl"));
            entity.setCreateUser(SYNC_USER);
            entity.setUpdateUser(SYNC_USER);
            entity.setUpdateTime(new Date());
            return entity;
        } catch (Exception e) {
            logger.error("【同步车型】精真估车系转换异常,json={},message:{}", obj.toJSONString(), e.getMessage());
        }
        return null;
    }

}
